<script lang="ts" setup>
import { useVbenModal } from '@vben/common-ui';

import { message } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import { postWxapps, putWxapps } from '#/api/plugin/wxapp';

const state = reactive({
  isUpdata: false,
});
const [Form, formApi] = useVbenForm({
  handleSubmit: onSubmit,
  schema: [
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入',
      },
      fieldName: 'name',
      label: '小程序名称',
      rules: 'required',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入',
      },
      fieldName: 'app_id',
      label: 'App ID',
      rules: 'required',
    },
    {
      component: 'InputPassword',
      componentProps: {
        placeholder: '请输入',
      },
      fieldName: 'app_secret',
      label: 'App Secret',
      rules: 'required',
    },
    {
      component: 'Switch',
      defaultValue: 0,
      componentProps: {
        checkedChildren: '是',
        unCheckedChildren: '否',
        checkedValue: 1,
        unCheckedValue: 0,
      },
      fieldName: 'is_default',
      label: '默认小程序',
    },
  ],
  showDefaultActions: false,
});
const [Modal, formModalApi] = useVbenModal({
  fullscreenButton: false,
  onCancel() {
    formModalApi.close();
  },
  onConfirm: async () => {
    await formApi.validateAndSubmitForm();
  },
  async onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const values: any = formModalApi.getData();
      if (values) {
        state.isUpdata = true;
        formApi.setValues(values);
      }
    }
  },
});

async function onSubmit(values: any) {
  function showMsg(msg: string) {
    message.success(msg);
    state.isUpdata = false;
    formModalApi.setData({ isUpdata: true });
    formModalApi.close();
  }
  if (state.isUpdata) {
    const { msg } = await putWxapps(values);
    showMsg(msg);
  } else {
    const { msg } = await postWxapps(values);
    showMsg(msg);
  }
}
</script>
<template>
  <Modal class="w-3/5">
    <Form />
  </Modal>
</template>

<style lang="scss" scoped></style>
